package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURL = request.getRequestURI();
        if(requestURL.contains("login"))
        {
            log.info("用户登陆: {}" , requestURL);
            filterChain.doFilter(request,response);
            return;
        }
        String jwt = request.getHeader("token");
        if(jwt == null || jwt.isEmpty())
        {
            log.info("请求头token不存在: {}" , requestURL);
            response.setStatus(401);
            return;
        }
        try
            {
                Claims claims = JwtUtils.parseToken(jwt);
                log.info("解析成功: {}" , claims);
                Integer i = claims.get("id", Integer.class);
                CurrentUserHoler.setCurrentUser(i);
            } catch (Exception e)
            {
                log.info("解析失败: {}" , e.getMessage());
                response.setStatus(401);
                return;
            }
        filterChain.doFilter(request,response);
        CurrentUserHoler.removeCurrentUser();
    }
}
